package com.jingran.satokennetty.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ChatHandler extends SimpleChannelInboundHandler<BinaryWebSocketFrame>{
    public static final ChannelGroup CLIENTS = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.info("channelActive");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest) {
            log.info("全类型消息");
        } else if(msg instanceof TextWebSocketFrame message){
            log.info("文本消息");
            ctx.writeAndFlush(new TextWebSocketFrame(message.text()));
        } else if(msg instanceof BinaryWebSocketFrame message){
            log.info("二进制消息！");
            ByteBuf byteBuf = Unpooled.directBuffer(message.content().capacity());
            byteBuf.writeBytes(message.content());
            ctx.writeAndFlush(new BinaryWebSocketFrame(byteBuf));
        }
        super.channelRead(ctx, msg);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, BinaryWebSocketFrame msg) {
        log.info("进入");
    }

    /**
     * 客户端创建的时候触发，当客户端连接上服务端之后，就可以获取该channel，然后放到channelGroup中进行统一管理
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        CLIENTS.add(ctx.channel());
        log.info("客户端连接，当前的连接的总数为：" + CLIENTS.size());
    }

    /**
     * 客户端销毁的时候触发
     * 当handlerRemoved 被触发时候，channelGroup会自动移除对应的channel
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        log.info("客户端断开，当前的连接的总数为：" + CLIENTS.size());
    }

}
